package team.bluepen.supermarket.web.servlet;

import team.bluepen.supermarket.constant.Error;
import team.bluepen.supermarket.constant.Role;
import team.bluepen.supermarket.data.entity.User;
import team.bluepen.supermarket.util.UserChecker;
import team.bluepen.supermarket.web.base.DataServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 添加用户
 * @author Kai
 */
@WebServlet(name = "UserAddServlet", value = "/api/user-add")
public class UserAddServlet extends DataServlet {
    /**用户名参数*/
    public static final String USERNAME_PARAM = "user_username";
    /**用户密码参数*/
    public static final String PASSWORD_PARAM = "user_password";
    /**用户角色参数*/
    public static final String ROLE_PARAM = "user_role";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        super.doPost(request, response);
        if (!checkUserRole(request)) {
            response.sendRedirect(requestSource);
            return;
        }

        String username = request.getParameter(USERNAME_PARAM);
        String password = request.getParameter(PASSWORD_PARAM);
        Role role = Role.get(request.getParameter(ROLE_PARAM));

        User user = new User()
                .setUsername(username)
                .setPassword(password)
                .setRole(role)
                .build();

        Error checkState = UserChecker.checkUser(user);
        if (!checkState.getState()) {
            response.sendRedirect(requestSource + "?error=" + checkState.getValue());
            return;
        }

        Error createState = userRepository.createUser(user);

        response.sendRedirect(requestSource + "?error=" + createState.getValue());
    }
}
